/**
 * 生成资源文件
 * **/
const path = require('path')
const fs = require('fs')
const projectDir = path.join(__dirname, '../src/assets/img')
const outputDir = path.join(__dirname, '../src/res.js')
let outputStr = ''
let category = {}

function readDir (currentDir, dirname = []) {
  try {
    const files = fs.readdirSync(currentDir)
    files.forEach(file => {
      // 判断文件是否是隐藏文件 .DS_Store 等等
      const isHideFile = file[0] === '.'
      if (isHideFile) return
      const url = path.join(currentDir, file) // 文件的全路径
      const stats = fs.statSync(url)
      const relativeUrl = path.relative(projectDir, url) // 相对目录)
      const relativeUrlArr = relativeUrl.split(/\\|\//)
      console.log(relativeUrlArr)
      if (stats.isDirectory()) {
        let tmp = category
        for (let i = 0; i < relativeUrlArr.length; i++) {
          const p = relativeUrlArr[i]
          tmp = tmp[p] ? tmp[p] : (tmp[p] = { root: {} })
        }
        dirname.push(file)
        readDir(url, dirname)
      } else {
        const dirArr = relativeUrlArr.slice(0, relativeUrlArr.length - 1)
        const extName = path.extname(file)
        let baseName = [...dirArr, path.basename(file, extName)]
        const regx = /[_-](\w)/ig
        baseName = baseName.join('-')
        const name = baseName.replace(regx, (str, word) => {
          return word.toUpperCase()
        })
        const f = relativeUrl.replace(/\\/ig, '/')
        outputStr += (`import ${name} from '@/assets/img/${f}'\r`)
        let tmp = null
        if (relativeUrlArr.length >= 2) {
          for (let i = 0; i < relativeUrlArr.length - 1; i++) {
            const p = relativeUrlArr[i]
            tmp = !tmp ? category[p] : tmp[p]
          }
        } else {
          tmp = category
        }
        tmp = tmp.root ? tmp.root : (tmp.root = {})
        tmp[name] = name
      }
    })
  } catch (e) {
    console.log(e)
    process.exit(0)
  }
}

function makeAsset () {
  outputStr = ''
  category = {}
  readDir(projectDir)

  let exportStr = `${outputStr}
export default ${JSON.stringify(category, null, 2)}
`
  exportStr = exportStr.replace(/"(\w+)"(:\s+"\w+")?/ig, '$1')
  // console.log(exportStr)
  fs.writeFileSync(outputDir, exportStr, {
    flag: 'w+'
  })
}

// fs.watch(projectDir, makeAsset)
makeAsset()
